package com.mysoft.gfyx.workbench.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysoft.framework.cache.api.CacheProvider;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.user.User;
import com.mysoft.framework.common.util.JsonUtil;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.core.function.authorization.AuthenticationUser;
import com.mysoft.framework.sdk.system.dto.UserDTO;
import com.mysoft.gfyx.common.rpc.mpapi.MpapiClientFactoryService;
import com.mysoft.gfyx.common.rpc.mpapi.MpapiClientService;
import com.mysoft.gfyx.common.rpc.mpapi.dto.ProfitRequestDto;
import com.mysoft.gfyx.common.rpc.mpapi.dto.SyncTenantProfitRequestDto;
import com.mysoft.gfyx.common.rpc.mpapi.dto.SyncTenantProfitResponseDto;
import com.mysoft.gfyx.common.rpc.omp.OMPClientFactoryService;
import com.mysoft.gfyx.common.rpc.omp.OMPClientService;
import com.mysoft.gfyx.common.rpc.omp.dto.CallbackRequestDto;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientFactoryService;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientService;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.SyncProfitRequestDto;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.SyncProfitResponseDto;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.UpdateOpptyStatusRequestDto;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.UpdateOpptyStatusResponseDto;
import com.mysoft.gfyx.common.rpc.ycgapi.YcgapiClientFactoryService;
import com.mysoft.gfyx.common.rpc.ycgapi.YcgapiClientService;
import com.mysoft.gfyx.common.rpc.ycgapi.dto.GetMemberInfoRespDto;
import com.mysoft.gfyx.common.util.LogUtil;
import com.mysoft.gfyx.workbench.controller.dto.NewTjProfitRequestDto;
import com.mysoft.gfyx.workbench.dao.PermTenantProfitDao;
import com.mysoft.gfyx.workbench.dao.PermTenantProfitLogDao;
import com.mysoft.gfyx.workbench.dao.entity.PermTenantProfit;
import com.mysoft.gfyx.workbench.dao.entity.PermTenantProfitLog;
import com.mysoft.gfyx.workbench.remoteservice.RemoteMySubscriptionService;
import com.mysoft.gfyx.workbench.remoteservice.WbRemoteSystemService;
import com.mysoft.gfyx.workbench.remoteservice.dto.GetUsersRequestDto;
import com.mysoft.gfyx.workbench.service.ProfitProduct.ClueRadarNationwide;
import com.mysoft.gfyx.workbench.service.ProfitProduct.ClueRadarProvince;
import com.mysoft.gfyx.workbench.service.ProfitProduct.MarketReport;
import com.mysoft.gfyx.workbench.service.ProfitProduct.UserAccount;
import com.mysoft.gfyx.workbench.service.ProfitProvinceService;
import com.mysoft.gfyx.workbench.service.ProfitService;
import com.mysoft.gfyx.workbench.service.dto.CheckUserAdditionResponseDto;
import com.mysoft.gfyx.workbench.service.dto.SetProductProfitDto;
import com.mysoft.gfyx.workbench.service.exception.InitTenantException;
import com.mysoft.sdk.context.core.ThreadContextHolder;
import com.mysoft.sdk.tenantplatform.provider.TenantInfoDto;
import com.mysoft.sdk.tenantplatform.tianji.provider.TianjiTenantPlatformProvider;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class ProfitServiceImpl implements ProfitService {

    @Value("${product-profit.market-report}")
    private String productProfitMarketReport;

    @Value("${product-profit.clue-radar-nationwide}")
    private String productProfitClueRadarNationwide;

    @Value("${product-profit.clue-radar-province}")
    private String productProfitClueRadarProvince;

    @Value("${product-profit.clue-radar-province-channel}")
    private String productProfitClueRadarProvinceChannel;

    @Value("${product-profit.user-account}")
    private String productProfitUserAccount;

    @Autowired
    private PermTenantProfitDao permTenantProfitDao;

    @Autowired
    private PermTenantProfitLogDao permTenantProfitLogDao;

    @Autowired
    private OMPClientFactoryService ompClientFactoryService;

    @Autowired
    private WbRemoteSystemService wbRemoteSystemService;

    @Autowired
    private RemoteMySubscriptionService remoteMySubscriptionService;

    @Autowired
    private ProfitProvinceService profitProvinceService;

    @Autowired
    private CacheProvider cacheProvider;

    @Autowired
    private ContextManager contextManager;

    @Autowired
    private MpapiClientFactoryService mpapiClientFactoryService;

    @Autowired
    private LogUtil logUtil;
    @Autowired
    private TianjiTenantPlatformProvider platformProvider;
    @Autowired
    private YcgapiClientFactoryService ycgapiClientFactoryService;
    @Autowired
    private OpptyServiceClientFactoryService opptyServiceClientFactoryService;

    public CheckUserAdditionResponseDto checkUserAddition() throws ParseException {
        List<PermTenantProfit> profits = getProfits();

        Integer totalNumber = getMaxUserNumber(profits);

        // 判断profit表是否有云采购的会员权益,如果没有,则调用一次云采购的接口,看看有没有权益
        // 如果有权益,则新增一条profit记录,并计算会员账号数时,加上该判断
        // 如果没有则忽略
        boolean hasYcgMember = false;
        for (PermTenantProfit item : profits) {
            if (item.getProductCode().equals(Product.YcgMemberAccount.toString())) {
                hasYcgMember = true;
                totalNumber += item.getNumber();
            }
        }

        if (!hasYcgMember) {
            TenantInfoDto tenantInfo = platformProvider.getTenantInfo(contextManager.fetchContextInfo().getTenantCode());
            YcgapiClientService ycgapiClientService = ycgapiClientFactoryService.getYcgapiClientService();
            GetMemberInfoRespDto memberInfo = ycgapiClientService.getMemberInfo(tenantInfo.getFullName());
//            GetMemberInfoRespDto memberInfo = ycgapiClientService.getMemberInfo("上海三菱电梯有限公司");
            if (memberInfo.getData() != null) {
                String accountCount = memberInfo.getData().get("account_count");
                String endAt = memberInfo.getData().get("end_at");
                if (accountCount != null && endAt != null && !endAt.equals("")) {
                    int accountNum = Integer.parseInt(accountCount);

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date endTime = sdf.parse(memberInfo.getData().get("end_at"));
                    if (!endTime.before(new Date())) {
                        //如果云采购的权益时间未过期，那么计算账号数
                        totalNumber += accountNum;

                        //并新增一条profit记录,并计算会员账号数时,加上该判断
                        try {
                            this.CreateYcgProfit(accountNum, memberInfo.getData().get("end_at"), memberInfo.getData().get("supplier_id"), memberInfo.getData().get("supplier_level"));
                        } catch (ParseException e) {
                            logUtil.info("用户事件", "调用云采购会员接口失败或格式错误:" + e.getMessage());
                        }
                    }
                }
            }
        }


        GetUsersRequestDto getUsersRequestDto = new GetUsersRequestDto();
        List<UserDTO> userDTOS = wbRemoteSystemService.GetUsers(getUsersRequestDto);
        Integer existUserCount = userDTOS.size();

        //以账号为admin为条件判断是否系统管理员,而非IsAdmin为条件
        for (int i = 0; i < existUserCount; i++) {
            if (userDTOS.get(i).getUserCode().equals("admin")) {
                existUserCount--;
            }
        }

        CheckUserAdditionResponseDto checkUserAdditionResponseDto = new CheckUserAdditionResponseDto();
        checkUserAdditionResponseDto.setOverLimitation(totalNumber <= existUserCount);
        checkUserAdditionResponseDto.setExistUserNumber(existUserCount);
        checkUserAdditionResponseDto.setMaxUserNumber(totalNumber);

        return checkUserAdditionResponseDto;
    }

    private void CreateYcgProfit(int accountNum, String endAt, String supplierId, String supplierLevel) throws ParseException {
        //先删除再新增，保证只有一条记录
        QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ProductCode", Product.YcgMemberAccount.toString());
        permTenantProfitDao.delete(queryWrapper);

        UUID userId = contextManager.fetchContextInfo().getUserContext().getUserId();
        if (userId == null || userId.toString().equals("")) {
            userId = UUID.fromString("00000000-0000-0000-0000-000000000000");
        }
        String userName = contextManager.fetchContextInfo().getUserContext().getUserName();
        if (userName.equals("")) {
            userName = "定时任务调度";
        }

        PermTenantProfit permTenantProfit = new PermTenantProfit();
        permTenantProfit.setPermTenantProfitGUID(UUID.randomUUID());
        permTenantProfit.setProfitName("云采购付费企业,供应商ID:" + supplierId + ",等级:" + supplierLevel);
        permTenantProfit.setProductCode(Product.YcgMemberAccount.toString());
        permTenantProfit.setNumber(accountNum);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        permTenantProfit.setEffectiveStartTime(new Date()); //实际不知道云采购付费企业的租期起始时间,这里以当前时间为起始时间
        permTenantProfit.setEffectiveEndTime(sdf.parse(endAt));
        permTenantProfit.setCreatedGUID(userId);
        permTenantProfit.setCreatedName(userName);
        permTenantProfit.setCreatedTime(new Date());

        permTenantProfitDao.insert(permTenantProfit);
    }

    public List<PermTenantProfit> getProfits() {
        QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDateStr = sdf.format(new Date());
        queryWrapper.le("EffectiveStartTime", nowDateStr);
        queryWrapper.ge("EffectiveEndTime", nowDateStr);

        List<PermTenantProfit> profits = permTenantProfitDao.selectList(queryWrapper);
        return profits;
    }

    protected Integer getMaxUserNumber(List<PermTenantProfit> profits) {
        Integer maxUserNumber = 0;

        ClueRadarNationwide clueRadarNationwide = new ClueRadarNationwide();
        maxUserNumber += clueRadarNationwide.getAccountNumber(profits);

        ClueRadarProvince clueRadarProvince = new ClueRadarProvince();
        maxUserNumber += clueRadarProvince.getAccountNumber(profits);

        MarketReport marketReport = new MarketReport();
        maxUserNumber += marketReport.getAccountNumber(profits);

        UserAccount userAccount = new UserAccount();
        maxUserNumber += userAccount.getAccountNumber(profits);

        return maxUserNumber;
    }

    public void initTenant(NewTjProfitRequestDto newTjProfitRequestDto) throws InitTenantException {
        log.info(JsonUtil.toString(newTjProfitRequestDto));
        List<String> errors = new LinkedList<>();
        newTjProfitRequestDto.getAppAuths().forEach(aa -> {
            aa.getAuths().forEach(a -> {
                if (aa.getAppCode().equals("4022") || aa.getAppCode().equals("0000")) return;

                SetProductProfitDto setProductProfitDto = new SetProductProfitDto();

                setProductProfitDto.setTaskId(newTjProfitRequestDto.getTaskId());
                setProductProfitDto.setProfitOutsideGUID(aa.getProductId());
                setProductProfitDto.setProfitOutsideCode(aa.getProductCode());
                setProductProfitDto.setDeliveryNo(newTjProfitRequestDto.getDeliveryNo());
                setProductProfitDto.setDeliveryBatchNo(newTjProfitRequestDto.getDeliveryBatchNo());
                setProductProfitDto.setNumber(Integer.parseInt(a.getAuthNum()));
                setProductProfitDto.setDeliveryAuthId(a.getAuthId());

                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date appEffectiveStartTime = sdf.parse(aa.getAppEffectiveStartTime());

                    // 当SignType为2时，代表是续约产品,(1是新签，3是增购)
                    if (a.getSignType().toString().equals("2")) {
                        // 获取该产品有效期最后的一条权益
                        PermTenantProfit permTenantProfit = getLatestProfitByCode(aa.getProductCode(), newTjProfitRequestDto.getDeliveryNo(), newTjProfitRequestDto.getDeliveryBatchNo());
                        // 如果当前产品支持的日期比这个权益的开始时间更晚，那么就需要更改这个的开始时间。会导致这个问题主要是业财的一些操作习惯。
                        if (permTenantProfit != null && permTenantProfit.getEffectiveEndTime().getTime() > appEffectiveStartTime.getTime()) {
                            appEffectiveStartTime = permTenantProfit.getEffectiveEndTime();
                        }
                    }
                    setProductProfitDto.setEffectiveEndTime(sdf.parse(aa.getAppEffectiveEndTime()));
                    setProductProfitDto.setEffectiveStartTime(appEffectiveStartTime);

                    setProductProfit(setProductProfitDto);
                } catch (ParseException e) {
                    errors.add("日期无法解析：" + aa.getAppEffectiveEndTime() + "，以及" + aa.getAppEffectiveStartTime());
                    return;
                } catch (Exception e) {
                    errors.add(e.getMessage());
                    return;
                }
            });
        });

        // 回调
        Object callbackResult = initTenantCallback(newTjProfitRequestDto.getTaskId(), errors);

        try {
            // 开启调度
            remoteMySubscriptionService.applyCron();

            // 重置时间
            profitProvinceService.resetModifiedDate();

            // 推送权益给小程序用户
            this.PushProfitToMiniProgram();

        } catch (Exception e) {
            errors.add(e.getMessage());
        }

        logInitiation(newTjProfitRequestDto, errors, callbackResult);

        if (!errors.isEmpty()) {
            throw new InitTenantException(StringUtil.join(errors.toArray()));
        }
    }

    protected PermTenantProfit getLatestProfitByCode(String productCode, String withoutSelfDeliveryNo, String withoutSelfDeliveryBatchNo) {
        QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ProfitOutsideCode", productCode);
        queryWrapper.and(qw -> {
            qw.ne("DeliveryNo", withoutSelfDeliveryNo).or().ne("DeliveryBatchNo", withoutSelfDeliveryBatchNo);
        });
        queryWrapper.orderByDesc("EffectiveEndTime");

        List<PermTenantProfit> profits = permTenantProfitDao.selectList(queryWrapper);
        if (profits != null && profits.size() > 0) {
            return profits.get(0);
        }
        return null;
    }

    /**
     * 查询租户所有的数据
     *
     * @return List<PermTenantProfit>
     */
    protected List<PermTenantProfit> getAllProfit() {
        QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("limit 1000");
        queryWrapper.orderByDesc("EffectiveEndTime");

        return permTenantProfitDao.selectList(queryWrapper);
    }

    public boolean checkProductCodeEffective(String code) {
        String tenantCode = contextManager.fetchContextInfo().getTenantCode();
        String cacheCode = tenantCode + "_profit_" + code;
        Boolean flag = cacheProvider.get(cacheCode);
        if (flag != null) {
            return flag;
        }
        QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = dateFormat.format(date);
        queryWrapper.like("ProductCode", "%" + code + "%");
        queryWrapper.gt("EffectiveEndTime", dateString);
        queryWrapper.le("EffectiveStartTime", dateString);
        queryWrapper.last("limit 1");
        queryWrapper.orderByDesc("EffectiveEndTime");
        PermTenantProfit profit = permTenantProfitDao.selectOne(queryWrapper);
        if (profit != null) {
            cacheProvider.set(cacheCode, true, 3600);
            return true;
        } else {
            cacheProvider.set(cacheCode, false, 3600);
            return false;
        }
    }

    public void logInitiation(NewTjProfitRequestDto request, List<String> errors, Object callbackResult) {
        PermTenantProfitLog permTenantProfitLog = new PermTenantProfitLog();
        permTenantProfitLog.setPermTenantProfitLogGUID(UUID.randomUUID());
        permTenantProfitLog.setCallbackData(JsonUtil.toString(callbackResult));
        permTenantProfitLog.setRequestData(JsonUtil.toString(request));
        permTenantProfitLog.setResponseData(JsonUtil.toString(errors));
        permTenantProfitLog.setDeliveryNo(request.getDeliveryNo());
        permTenantProfitLog.setTaskId(request.getTaskId());

        permTenantProfitLogDao.insert(permTenantProfitLog);
    }

    protected Object initTenantCallback(String taskId, List<String> errors) {
        CallbackRequestDto callbackRequestDto = new CallbackRequestDto();
        callbackRequestDto.setTaskId(taskId);
        Integer status = errors.isEmpty() ? 1 : 2;
        callbackRequestDto.setTaskStatus(status);

        OMPClientService ompClientService = ompClientFactoryService.getOMPService();
        Object result = new HashMap<>();
        try {
            result = ompClientService.executeResultCallback(callbackRequestDto);
        } catch (Exception e) {
            result = e.toString();
        }
        return result;
    }

    protected void setProductProfit(SetProductProfitDto setProductProfitDto) {
        String productCode = setProductProfitDto.getProfitOutsideCode();

        if (productCode.equals(productProfitMarketReport)) {
            setProductProfitDto.setProductCode(Product.MarketReport.toString());
            setProductProfitDto.setProfitName("市场洞察");
        } else if (productCode.equals(productProfitClueRadarProvince) || productCode.equals(productProfitClueRadarProvinceChannel)) {
            setProductProfitDto.setProductCode(Product.ClueRadarProvince.toString());
            setProductProfitDto.setProfitName("线索雷达省份版");
        } else if (productCode.equals(productProfitClueRadarNationwide)) {
            setProductProfitDto.setProductCode(Product.ClueRadarNationwide.toString());
            setProductProfitDto.setProfitName("线索雷达全国版");
        } else if (productCode.equals(productProfitUserAccount)) {
            setProductProfitDto.setProductCode(Product.UserAccount.toString());
            setProductProfitDto.setProfitName("单独账户购买");
        } else {
            log.error("购买的商品ID在配置中不存在，请联系系统管理员。");
            throw new BusinessLogicException("购买的商品ID在配置中不存在，请联系系统管理员。");
        }

        saveProductProfit(setProductProfitDto);
    }

    protected void saveProductProfit(SetProductProfitDto setProductProfitDto) {
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        PermTenantProfit permTenantProfit = MappingUtil.getSimpleMapperFacade().map(setProductProfitDto, PermTenantProfit.class);

        QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DeliveryNo", setProductProfitDto.getDeliveryNo());
        queryWrapper.eq("DeliveryBatchNo", setProductProfitDto.getDeliveryBatchNo());
        // 一次可能发几个产品
        queryWrapper.eq("DeliveryAuthId", setProductProfitDto.getDeliveryAuthId());
        queryWrapper.last("limit 1");
        PermTenantProfit existPermTenantProfit = permTenantProfitDao.selectOne(queryWrapper);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OpptyServiceClientService opptyService = opptyServiceClientFactoryService.getOpptyServiceClientService();
        SyncProfitRequestDto requestDto = new SyncProfitRequestDto();
        requestDto.setProduct_code(setProductProfitDto.getProductCode());
        requestDto.setDelivery_auth_id(setProductProfitDto.getDeliveryAuthId());
        requestDto.setDelivery_no(setProductProfitDto.getDeliveryNo());
        requestDto.setDelivery_batch_no(setProductProfitDto.getDeliveryBatchNo());
        requestDto.setNumber(setProductProfitDto.getNumber());
        requestDto.setStart_time(format.format(setProductProfitDto.getEffectiveStartTime()));
        requestDto.setEnd_time(format.format(setProductProfitDto.getEffectiveEndTime()));
        requestDto.setOperator_guid(authenticationUser.getUserId().toString());
        requestDto.setOperator_name(authenticationUser.getUserName());
        if (existPermTenantProfit == null) {
            UUID newProfitGuid = UUID.randomUUID();
            permTenantProfit.setPermTenantProfitGUID(newProfitGuid);
            permTenantProfit.setCreatedGUID(authenticationUser.getUserId());
            permTenantProfit.setCreatedName(authenticationUser.getUserName());
            permTenantProfit.setCreatedTime(new Date());

            permTenantProfitDao.insert(permTenantProfit);
            requestDto.setProfit_guid(newProfitGuid.toString());
        } else {
            permTenantProfit.setPermTenantProfitGUID(existPermTenantProfit.getPermTenantProfitGUID());
            permTenantProfit.setModifiedGUID(authenticationUser.getUserId());
            permTenantProfit.setModifiedName(authenticationUser.getUserName());
            permTenantProfit.setModifiedTime(new Date());

            permTenantProfitDao.updateById(permTenantProfit);
            requestDto.setProfit_guid(permTenantProfit.getPermTenantProfitGUID().toString());
        }
        SyncProfitResponseDto res = opptyService.syncProfit(requestDto);
        logUtil.info("syncProfit", "同步租户权益:请求参数:" + JSON.toJSONString(requestDto) + ",响应:" + JSON.toJSONString(res));
    }

    @Override
    public boolean PushProfitToMiniProgram() throws Exception {
        // 获取租户 code
        String tenantCode = contextManager.fetchContextInfo().getTenantCode();
        // 查找当前的权益数据进行推送
        List<PermTenantProfit> profits = this.getAllProfit();

        if (profits.size() <= 0) {
            logUtil.info("init-tenant", "暂没有发现权益");
            return true;
        }

        MpapiClientService remoteService = mpapiClientFactoryService.getMpapiClientService();

        List<ProfitRequestDto> profitRequestDtoList = new ArrayList<ProfitRequestDto>();
        profits.forEach(permTenantProfit -> {
            ProfitRequestDto profitRequestDto = new ProfitRequestDto();
            profitRequestDto.setUid(permTenantProfit.getPermTenantProfitGUID().toString());
            profitRequestDto.setProfit_outside_uid(permTenantProfit.getProfitOutsideGUID());
            profitRequestDto.setProfit_outside_code(permTenantProfit.getProfitOutsideCode());
            profitRequestDto.setProfit_name(permTenantProfit.getProfitName());
            profitRequestDto.setProduct_code(permTenantProfit.getProductCode());
            profitRequestDto.setEffective_start_time(DateFormatUtils.format(permTenantProfit.getEffectiveStartTime(), "yyyy-MM-dd HH:mm:SS"));
            profitRequestDto.setEffective_end_time(DateFormatUtils.format(permTenantProfit.getEffectiveEndTime(), "yyyy-MM-dd HH:mm:SS"));
            profitRequestDtoList.add(profitRequestDto);
        });

        SyncTenantProfitRequestDto requestDto = new SyncTenantProfitRequestDto();
        requestDto.setTenant_Code(tenantCode);
        requestDto.setProfit(profitRequestDtoList);

        SyncTenantProfitResponseDto resp = remoteService.syncTenantProfit(requestDto);

        if (resp.isSuccess()) {
            return true;
        } else {
            logUtil.info("init-tenant", resp.getMessage());
            return false;
        }
    }

    @Override
    public boolean pullYcgMemberProfit() throws Exception {
        TenantInfoDto tenantInfo = platformProvider.getTenantInfo(contextManager.fetchContextInfo().getTenantCode());
        YcgapiClientService ycgapiClientService = ycgapiClientFactoryService.getYcgapiClientService();
        GetMemberInfoRespDto memberInfo = ycgapiClientService.getMemberInfo(tenantInfo.getFullName());
//        GetMemberInfoRespDto memberInfo = ycgapiClientService.getMemberInfo("上海三菱电梯有限公司");
        if (memberInfo.getData() != null) {

            String accountCount = memberInfo.getData().get("account_count");
            String endAt = memberInfo.getData().get("end_at");
            if (accountCount == null || accountCount.equals("") || endAt == null || endAt.equals("")) {
                //没有取到账号数量、权益结束时间,直接返回
                return false;
            }
            int accountNum = Integer.parseInt(accountCount);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date endTime = sdf.parse(memberInfo.getData().get("end_at"));
            if (endTime.before(new Date())) {
                //权益时间已经过期，那么也直接返回
                return false;
            }

            QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ProductCode", Product.YcgMemberAccount.toString());
            List<PermTenantProfit> profits = permTenantProfitDao.selectList(queryWrapper);
            if (profits == null || profits.size() != 1) {
                //没有云采购会员的权益或权益数量超过1条,新增一条
                this.CreateYcgProfit(accountNum, memberInfo.getData().get("end_at"), memberInfo.getData().get("supplier_id"), memberInfo.getData().get("supplier_level"));
            } else {
                // 有且只有1条云采购的会员权益,比对一下权益结束时间和账号数量,如果不一致,则更新记录
                PermTenantProfit ycgProfit = profits.get(0);
                if (!ycgProfit.getNumber().equals(accountNum) || !ycgProfit.getEffectiveEndTime().equals(endTime)) {
                    ycgProfit.setNumber(accountNum);
                    ycgProfit.setEffectiveEndTime(endTime);
                    permTenantProfitDao.updateById(ycgProfit);
                }
            }
        }
        return true;
    }
}
